package com.mbl.base.modular.base.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mbl.base.modular.base.entity.Region;
import com.mbl.base.modular.base.service.IRegionService;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import com.mbl.base.core.common.controller.BaseController;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 行政区域表 前端控制器
 * </p>
 *
 * @author lwj
 * @since 2020-03-24
 */
@RestController
@RequestMapping("/base/region")
public class RegionController extends BaseController<Region, IRegionService> {

    @Override
    public void machiningList(QueryWrapper<Region> queryWrapper, String condition) {
        super.machiningList(queryWrapper, condition);
    }

    @Override
    public void machiningListResult(IPage<Region> page1) {
        final List<Region> records = page1.getRecords();
//        records.stream().map(this::handleChildren).collect(Collectors.toList());
        page1.setRecords(handleChildren2(records));
        super.machiningListResult(page1);
    }

    private Region handleChildren(Region region){
        if(region.getType() == 3){
            return null;
        }
        final List<Region> regions = getService().query().eq("pid", region.getId()).list();
        if(regions == null || regions.size() < 1){
            return null;
        }
        regions.stream().map(this::handleChildren).collect(Collectors.toList());
        region.setChildren(regions);
        return region;
    }

    private List<Region> handleChildren2(List<Region> regions){
        // 获取所有一级节点
        final List<Region> collect1 = regions.stream().filter(region1 -> region1.getType() == 1).collect(Collectors.toList());
        // 删除总数组里面所有一级节点
        regions.removeAll(collect1);
        // 遍历一级节点
        collect1.forEach(region1 -> {
            // 取出一级节点对应的所有二级节点
            final List<Region> collect2 = regions.stream().filter(region2 -> {
                return region2.getType() == 2 && region2.getPid() == region1.getId();
            }).collect(Collectors.toList());
            // 删除总数组里面对应二级节点
            regions.removeAll(collect2);
            // 遍历二级节点
            collect2.forEach(region2 -> {
                // 取出二级节点对应的三级节点
                final List<Region> collect3 = regions.stream().filter(region3 -> {
                    return region3.getType() == 3 && region3.getPid() == region2.getId();
                }).collect(Collectors.toList());
                // 删除总数组里面对应三级节点
                regions.removeAll(collect3);
                // 二级节点赋值
                region2.setChildren(collect3);
            });
            // 一级节点赋值
            region1.setChildren(collect2);
        });
        return collect1;
    }
}

